/**
 * 
 */
package com.py.credit.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.Database;
import com.py.credit.entity.SContentInfo;
import com.py.credit.entity.common.TreeObj;
import com.py.credit.service.BatchLogService;
import com.py.credit.service.ContentService;
import com.py.credit.service.DataQualityService;
import com.py.credit.service.DataRelateService;
import com.py.credit.service.DbService;
import com.py.credit.service.DeptService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.TreeUtils;
import com.py.framework.core.entity.SysOfficeEntity;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * @author dd
 *
 */
@RestController
@RequestMapping(value = "/contentPanel")
public class ContentPanelController {

	@Autowired
	private ContentService contentService;

	@Autowired
	private BatchLogService batchLogService;
	@Autowired
	DeptService deptService;

	@Autowired
	private DbService dbService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private DataRelateService dataRelateService;
	@Autowired
	private DataQualityService dataQualityService;

	@Value("${tree.root.node}")
	private String nodeName;

	/**
	 * @api {get} /contentPanel/getContentResourceNum.json 获取目录数量
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 目录看板
	 *
	 * @apiParam {String} kId 数据库 id(可选)
	 * @apiParam {String} regionId 区域id(可选)
	 *
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json}成功返回结果:
	 *                    {"code":0,"msg":null,"count":0,"data":[{"num":3,"TYPE":"K"},{"num":116,"TYPE":"T"},{"num":2015,"TYPE":"M"},{"num":12,"TYPE":"D"}]}
	 */

	@RequestMapping(value = "/getContentResourceNum.json")
	public RestServiceResult<List<Map<String, Object>>> getContentResourceNum(
			@RequestParam(value = "kId", defaultValue = "", required = false) String kId,
			@RequestParam(value = "regionId", defaultValue = "", required = false) String regionId) {

		List<Map<String, Object>> contentResouceNum = null;

		if (StringUtils.isBlank(regionId)) {

			contentResouceNum = contentService.getCommonContentResouceNum(kId);

		} else {

			contentResouceNum = contentService.getBookContentResouceNum(kId, regionId);

		}

		return new RestServiceResult<List<Map<String, Object>>>(contentResouceNum);

	}

	/**
	 * @api {get} /contentPanel/getContentRadialTree.json 获取目录径向图
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 目录看板
	 *
	 * @apiParam {String} kId 数据库 id(可选)
	 * @apiParam {String} regionId 区域id(可选)
	 * @apiParam {String} regionName 区域名称(可选)
	 *
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json}成功返回结果:
	 *                    {"code":0,"msg":null,"count":0,"data":[]}
	 * 
	 */

	@RequestMapping(value = "/getContentRadialTree.json")
	public RestServiceResult<Map<String, Object>> getContentStatistics(
			@RequestParam(value = "kId", defaultValue = "", required = false) String kId,
			@RequestParam(value = "regionId", defaultValue = "", required = false) String regionId,
			@RequestParam(value = "regionName", defaultValue = "", required = false) String regionName) {

		List<TreeObj> data = null;

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, TreeObj> temp = new HashMap<String, TreeObj>();
		List<TreeObj> panelData = new ArrayList<TreeObj>();

		if (StringUtils.isBlank(regionId)) {

			data = TreeUtils.getTree(contentService.getCommonContent(kId));

			SContentInfo sf = contentService.getCommonContentInfo();

			if (sf != null) {

				if (StringUtils.isBlank(kId)) {

					for (TreeObj node : data) {

						String deptId = node.getId().split("_")[1];

						List<TreeObj> children = node.getChildren();

						if (temp.containsKey(deptId)) {

							TreeObj treeObj = temp.get(deptId);

							treeObj.getChildren().addAll(children);

						} else {

							panelData.add(node);

							temp.put(deptId, node);
						}

					}

					map.put("name", sf.getName() + "径向树");

					TreeObj node = new TreeObj();

					node.setName(sf.getName());

					node.setChildren(panelData);

					map.put("nodes", node);

				} else {

					List<Database> dbList = dbService.getDbList(kId);

					map.put("name", sf.getName() + dbList.get(0).getName() + "径向树");

					TreeObj node = new TreeObj();

					node.setName(dbList.get(0).getName());

					node.setChildren(data);

					map.put("nodes", node);

				}
			}

		} else {

			List<TreeObj> boookContentByRegionId = contentService.getBoookContentByRegionId(regionId);

			data = TreeUtils.getTree(boookContentByRegionId);

			if (StringUtils.isBlank(kId)) {

				for (TreeObj node : data) {

					String deptId = node.getId().split("_")[1];

					List<TreeObj> children = node.getChildren();

					if (temp.containsKey(deptId)) {

						TreeObj treeObj = temp.get(deptId);

						treeObj.getChildren().addAll(children);

					} else {

						panelData.add(node);

						temp.put(deptId, node);
					}

				}

				map.put("name", regionName + "径向树");

				TreeObj node = new TreeObj();

				node.setName(regionName);

				node.setChildren(panelData);

				map.put("nodes", node);

			} else {

				List<TreeObj> filter = new ArrayList<TreeObj>();

				List<Database> dbList = dbService.getDbList(kId);

				map.put("name", regionName + dbList.get(0).getName() + "径向树");

				TreeObj node = new TreeObj();

				node.setName(dbList.get(0).getName());

				for (TreeObj obj : boookContentByRegionId) {

					if (kId.equals(obj.getRootId())) {

						filter.add(obj);
					}

				}

				node.setChildren(TreeUtils.getTree(filter));

				map.put("nodes", node);

			}

		}

		return new RestServiceResult<Map<String, Object>>(map);

	}

	/**
	 * @api {get} /contentPanel/getCommonContentTableNum.json 获取表资源数量
	 * @apiName getCommonContentTableNum
	 * @apiVersion 0.0.1
	 * @apiGroup 目录看板
	 *
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json}成功返回结果:
	 *                    {"code":0,"msg":null,"count":0,"data":[{"num":116,"name":"法人库"},{"num":0,"name":"自然人库"},{"num":0,"name":"非企业法人库"}]}
	 */

	@RequestMapping(value = "/getCommonContentTableNum.json")
	public RestServiceResult<List<Map<String, Object>>> getCommonContentTableNum() {

		List<Map<String, Object>> commonContentTableNum = contentService.getCommonContentTableNum();

		return new RestServiceResult<List<Map<String, Object>>>(commonContentTableNum);

	}

	/**
	 * @api {get} /contentPanel/getCollectionInfo.json 获取归集信息
	 * @apiName getCollectionInfo
	 * @apiVersion 0.0.1
	 * @apiGroup 目录看板
	 *
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json}成功返回结果:
	 *                    {"code":0,"msg":null,"count":0,"data":{"wcount":0,"total":57,"rcount":41,"scount":16,"fcount":0}}
	 */

	@RequestMapping(value = "/getCollectionInfo.json")
	public RestServiceResult<Map<String, Object>> getCollectionInfo() {

		Map<String, Object> collectionInfo = batchLogService.getCollectionInfo();

		int unableAuthZooRecord = dataRelateService.getUnableAuthZooRecord();

		collectionInfo.put("wcount", unableAuthZooRecord);

		collectionInfo.put("qualityReport", dataQualityService.getQulityReportNum());

		RestServiceResult<Integer> dataCollectionMessageNum = remoteBaseService.getDataCollectionMessageNum();

		if (RestServiceResult.CODE_SUCCESS == dataCollectionMessageNum.getCode()) {

			collectionInfo.put("dataCollection", dataCollectionMessageNum.getData());

		}

		return new RestServiceResult<Map<String, Object>>(collectionInfo);

	}

	/**
	 * @api {get} /contentPanel/getCommonContentDept.json 获取信源单位
	 * @apiName getCommonContentDept
	 * @apiVersion 0.0.1
	 * @apiGroup 目录看板
	 *
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json}成功返回结果:
	 *                    {"code":0,"msg":null,"count":0,"data":{"id":null,"rootId":null,"name":"吉林省","url":null,"type":null,"pId":null,"sort":null,"children":[{"id":null,"rootId":null,"name":"信用中心","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"中心2","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"发展改革委","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"安监局","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"公安局","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"省工商局","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"行业协会","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"专业服务商","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"第三方机构","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"公司自有数据","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"行业协会待清洗","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null},{"id":null,"rootId":null,"name":"信用中心二级部门","url":null,"type":null,"pId":null,"sort":null,"children":null,"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null}],"extend":null,"icon":null,"checked":null,"nocheck":null,"open":false,"isParent":null}}
	 */

	@RequestMapping(value = "/getCommonContentDept.json")
	public RestServiceResult<TreeObj> getCommonContentDept() {

		List<TreeObj> nodes = contentService.getCommonContentDept();

		TreeObj rootNode = new TreeObj(nodeName, nodes);

		return new RestServiceResult<TreeObj>(rootNode);

	}

	/**
	 * @api {get} /contentPanel/getCollectionAnalysis.json 获取归集类型分析数据
	 * @apiName getCollectionAnalysis
	 * @apiVersion 0.0.1
	 * @apiGroup 目录看板
	 *
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json}成功返回结果:
	 *                    {"code":0,"msg":null,"count":0,"data":[{"wcount":0,"tcount":59,"rcount":43,"scount":16,"typeCN":"导入","fcount":0},{"wcount":0,"tcount":2,"rcount":2,"scount":0,"typeCN":"接口","fcount":0}]}
	 */

	@RequestMapping(value = "/getCollectionAnalysis.json")
	public RestServiceResult<List<Map<String, Object>>> getCollectionAnalysis() {

		List<Map<String, Object>> collectionInfo = batchLogService.getCollectionAnalysis();

		return new RestServiceResult<List<Map<String, Object>>>(collectionInfo);

	}

	/**
	 * @api {get} /contentPanel/getDeptRkNum.json 获取部门入库数量
	 * @apiName getDeptRkNum
	 * @apiVersion 0.0.1
	 * @apiGroup 目录看板
	 *
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json}成功返回结果:
	 *                    {"code":0,"msg":null,"count":0,"data":[{"tcount":61,"scount":16,"deptName":"信用中心"}]}
	 */

	@RequestMapping(value = "/getDeptRkNum.json")
	public RestServiceResult<List<Map<String, Object>>> gettDeptRkNum(HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		try {
			RestServiceResult<List<SysOfficeEntity>> depts = remoteBaseService.getOfficesByAreaId(null,
					HttpServletHelper.getUserToken(request));
			if (RestServiceResult.CODE_SUCCESS != depts.getCode()) {
				result.setCode(depts.getCode());
				result.setMsg(depts.getMsg());
				return result;
			}
			List<SysOfficeEntity> deptInfo = depts.getData();
			List<Map<String, Object>> deptRkNum = new ArrayList<Map<String, Object>>();
			// 填充部门名称
			if (null != deptInfo) {
				deptRkNum = batchLogService.getDeptRkNum();
				for (Iterator<Map<String, Object>> it = deptRkNum.listIterator(); it.hasNext();) {
					Map<String, Object> map = it.next();
					if (null != map && StringUtils.isNotBlank(String.valueOf(map.get("deptId")))) {

						for (SysOfficeEntity office : deptInfo) {

							if (String.valueOf(office.getId()).equals(String.valueOf(map.get("deptId")))) {

								map.put("deptName", office.getOfficeName());

								break;

							}

						}

					} else {
						// 未查到部门信息的数据删除
						it.remove();
					}
				}
			}
			result.setData(deptRkNum);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取部门入库数量异常，请稍后再试！");
			ExceptionLogger.error("获取部门入库数量异常！", e.getMessage(), e);
			return result;
		}
	}
}
